package top.hmtools.wxmp.webpage.tools;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;


/**
 * MAP操作相关工具类
 * @author Hybomyth
 * 创建日期：2016-12-12上午9:28:47
 */
public class MapTools {

	/**
	 * 获取字典排序的字符串
	 * @param param	
	 * @param k_v	键值对之间的连接符，默认：=
	 * @param i_i	成员数据之间的连接符，默认：&
	 * @return
	 */
	public static String getOrderDictStr(TreeMap<String, String> param,String k_v,String i_i){
		StringBuffer sb_result = new StringBuffer();
		if(StringUtils.isBlank(k_v)){
			k_v = "=";
		}
		if(StringUtils.isBlank(i_i)){
			i_i = "&";
		}
		try {
			Set<Entry<String, String>> param_se = param.entrySet();
			Iterator<Entry<String, String>> param_ite = param_se.iterator();
			while(param_ite.hasNext()){
				Entry<String, String> item = param_ite.next();
				String key = item.getKey();
				String value = item.getValue();
				
				sb_result.append(key+k_v+value);
				if(param_ite.hasNext()){
					sb_result.append(i_i);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb_result.toString();
	}
	
	/**
	 * 获取过滤后的map
	 * @param sourceMap	需要过滤的map数据
	 * @param filters	用于过滤的key列表
	 * @return
	 */
	public static <T,E> Map<T,E> getFilterMap(Map<T,E> sourceMap,List<T> filters){
		Map<T,E> result = new HashMap<T,E>();
		try {
			Set<Entry<T,E>> entrySet = sourceMap.entrySet();
			Iterator<Entry<T, E>> iterator = entrySet.iterator();
			while(iterator.hasNext()){
				Entry<T, E> item = iterator.next();
				T key = item.getKey();
				E value = item.getValue();
				if(filters != null && filters.size()>0){
					if(!filters.contains(key)){
						result.put(key, value);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 将其它 Map 的实现类 转换为 treemap
	 * @param map
	 * @return
	 */
	public static <T, E> TreeMap<T, E> getTreeMap(Map<T,E> map){
		TreeMap<T, E> result = new TreeMap<T,E>();
		try {
			Set<Entry<T, E>> map_es = map.entrySet();
			Iterator<Entry<T, E>> map_ite = map_es.iterator();
			while(map_ite.hasNext()){
				Entry<T, E> item = map_ite.next();
				result.put(item.getKey(), item.getValue());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 *  遍历打印map
	 * @param map
	 */
	public static <K,V> void println(Map<K, V> map) {
		for(Entry<K, V> item:map.entrySet()){
			System.out.println("(key)"+item.getKey()+" ------->>  (value)"+item.getValue());
		}
	}
}
